import Cascader from "ant-design-vue/es/cascader";
import "ant-design-vue/lib/cascader/style/css";

export default {
  name: "FormCascader",
  props: {
    option: {
      type: Object,
      default() {
        return {};
      }
    },
    value: [String, Array]
  },
  model: {
    prop: "value",
    event: "updata"
  },
  data() {
    return {
      data: []
    };
  },
  computed: {
    fieldNames() {
      const valueField = this.option.valueField ? this.option.valueField : "id";
      const childrenField = this.option.childrenField
        ? this.option.childrenField
        : "children";
      const textField = this.option.textField ? this.option.textField : "text";
      return { label: textField, value: valueField, children: childrenField };
    }
  },
  created() {
    if (this.option.data) {
      this.setData(this.option.data);
    }
  },
  methods: {
    onChange(value) {
      this.$emit("updata", value);
      this.$emit("change", value);
    },
    setFocus(is) {
      if (is) {
        this.$refs.formSelect.focus();
      } else {
        this.$refs.formSelect.blur();
      }
    },
    setData(data) {
      this.data = data;
    }
  },
  render() {
    const that = this;
    const props = {
      ref: "formSelect",
      props: {
        ...this.option.props,
        options: this.data,
        fieldNames: this.fieldNames
      },
      on: {
        ...this.option.on,
        change: e => {
          that.onChange(e);
        },
        focus: e => {
          this.$emit("focus", e);
        },
        blur: e => {
          this.setFocus(false);
          this.$emit("blur", e);
        }
      }
    };
    if (typeof this.value === "object") {
      props.props.value = this.value;
    } else if (typeof this.value === "number") {
      props.props.value = this.value + "";
    }

    return <Cascader {...props} />;
  }
};
